package com.hl.domain;

//import com.sun.org.slf4j.internal.LoggerFactory;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
//import org.mybatis.logging.LoggerFactory;

import javax.websocket.Session;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public final class WebSocketUtils {
    private static final Logger logger = LoggerFactory.getLogger(WebSocketUtils.class);
    //用户名和session会话的映射关系
    public static  final Map<String, Session> user_session=new ConcurrentHashMap<>();

    //发送信息，先找到session，再发送消息
    public static R sendMessage(String userName,String message){
        Session session = user_session.get(userName);
        if (session == null) {
            return R.error("用户不在线");
        }
        if (!session.isOpen()) {
            user_session.remove(userName);
            return R.error("会话已关闭");
        }
        try {
            session.getBasicRemote().sendText(message);
            return R.ok();
        } catch (IOException e) {
            return R.error("发送失败");
        }
    }
    //扩展，广播消息
    public static void  sendAll(String message){
        user_session.forEach((userName,session)->{
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }
}
